package cs575.wido.action;

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JOptionPane;

import cs575.wido.UserSession;
import cs575.wido.WebServiceFactory;
import cs575.wido.ui.HomeWindow;
import cs575.wido.ui.LoginWindow;
import javax.jws.WebService;
import javax.xml.ws.WebServiceException;


public class LoginAction extends AbstractAction {

	protected final LoginWindow parent;
	
	public LoginAction(final LoginWindow parent) {
		this.parent = parent;
		putValue(NAME, "Login");
	}
	
	@Override
	public void actionPerformed(ActionEvent arg0) {
		login(parent.getUsername(), parent.getPassword());
	}

	// TODO modify this
	private void login(String username, String password) {
		cs575.client.Session session = null;
		
		try {
			cs575.client.WiDo wido = WebServiceFactory.getPort();
			session = wido.login(username, password);
		}
		catch (WebServiceException ex) {
			JOptionPane.showMessageDialog(this.parent, "Network Connection Problem");
		}
		
		if (session != null) {
			// setup UserSession here
			UserSession userSession = UserSession.getInstance();
			userSession.setUsername(username);
			userSession.setSession(session);
			
			HomeWindow homeWindow = new HomeWindow();
			homeWindow.setVisible(true);
			
			parent.dispose(); // get rid of login window
		}
		else {
			JOptionPane.showMessageDialog(this.parent, "Login Failed");
		}
	}
}
